package com.javaeye.chenweihuacwh.dao.baseData;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.chenweihuacwh.dto.DTO;
import com.javaeye.chenweihuacwh.dto.baseData.Logistics;

public class LogisticsDAOHibernate extends HibernateDaoSupport implements LogisticsDAO {
	
	public long getAllCount(final DTO contidions) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Logistics logistics = (Logistics)contidions;
				Criteria crit = session.createCriteria(Logistics.class);
				if (!"".equals(logistics.getName().trim())) {
					crit.add(Restrictions.like("name", "%" + logistics.getName().trim() + "%"));
				}
				if (!"-1".equals(logistics.getCategory().trim())) {
					crit.add(Restrictions.eq("category", logistics.getCategory().trim()));
				}
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action).size();
	}
	
	public List getPageData(final DTO contidions, final int pageIndex, final int pageSize) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Logistics logistics = (Logistics)contidions;
				Criteria crit = session.createCriteria(Logistics.class);
				if (!"".equals(logistics.getName().trim())) {
					crit.add(Restrictions.like("name", "%" + logistics.getName().trim() + "%"));
				}
				if (!"-1".equals(logistics.getCategory().trim())) {
					crit.add(Restrictions.eq("category", logistics.getCategory().trim()));
				}
				crit.setFirstResult(pageIndex * pageSize);
				crit.setMaxResults(pageSize);
				return crit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}
	
	@Override
	public void saveLogistics(Logistics logistics) {
		getHibernateTemplate().saveOrUpdate(logistics);
		logger.debug("Product id set to: " + logistics.getId());
	}

	@Override
	public Logistics getLogistics(int id) {
		return (Logistics)getHibernateTemplate().get(Logistics.class, id);
	}

	@Override
	public void removeLogistics(int id) {
		Object o = getHibernateTemplate().get(Logistics.class, id);
		getHibernateTemplate().delete(o);
	}

}
